var express = require('express');
var router = express.Router();
const dbconfig =require('../util/dbconfig')

//新增，编辑
router.post('/add',(req,res,next)=>{
  var id =req.body.id
  console.log('id',id);
  if(id){
    //编辑
    var page =req.body.page
    var title =req.body.title
    var content =req.body.content
    let sql = "update article set title = ?,content =? where id =?"
    let sqlArr = [title,content,id]
    let callback =(err,data)=>{
      if(err){
        console.log('修改失败');
      }else{
        res.redirect('/?page='+page)
      }
    }
    dbconfig.sqlConnect(sql,sqlArr,callback);
  }else{
    //新增
    console.log('iiiiiiiiiiiiid',id);
    var data = {
      title:req.body.title,
      content:req.body.content,
      id:Date.now(),
      username : req.session.username
    }
    let sql ='insert into article(title,content,id,username) values(?,?,?,?)'
    let sqlArr = [data.title,data.content,data.id,data.username]
    let callBack = (err,data)=>{
      if(err){
        console.log(err);
        res.redirect('/write')
      }else{
        res.redirect('/')
        console.log(data);
      }
    }
    dbconfig.sqlConnect(sql,sqlArr,callBack);
  }
})

//删除的路由
router.get('/delete',(req,res)=>{
  var id=req.query.id
  var page = req.query.page
  let sql ='delete from article where id=?'
  let sqlArr = [id]
  let callBack = (err,data)=>{
    if(err){
      console.log('删除失败');
    }else{
      res.redirect('/?page='+page)
      console.log('删除成功');
    }
  }
  dbconfig.sqlConnect(sql,sqlArr,callBack);
})




module.exports = router;
